package com.ws.gold.config;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author ws
 * @create 2025/6/16
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        if (getFieldType(metaObject,"createTime") == LocalDateTime.class) {
            this.setFieldValByName("createTime", LocalDateTimeUtil.now(), metaObject);
            this.setFieldValByName("updateTime", LocalDateTimeUtil.now(), metaObject);
        }else {
            this.setFieldValByName("createTime", DateUtil.date(), metaObject);
            this.setFieldValByName("updateTime", DateUtil.date(), metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (getFieldType(metaObject,"createTime") == LocalDateTime.class) {
            this.setFieldValByName("updateTime", LocalDateTimeUtil.now(), metaObject);
        }else {
            this.setFieldValByName("updateTime", DateUtil.date(), metaObject);
        }
    }

    /**
     * 安全获取字段类型
     */
    private Class<?> getFieldType(MetaObject metaObject, String fieldName) {
        if (metaObject.hasGetter(fieldName)) {
            return metaObject.getGetterType(fieldName);
        }
        // 当无法获取类型时，尝试从值判断（批量操作可能为空）
        Object value = this.getFieldValByName(fieldName, metaObject);
        return value != null ? value.getClass() : LocalDateTime.class; // 默认返回 LocalDateTime
    }

}
